package be.vdab.dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import be.vdab.entities.Persoon;

@Repository("persoonDAOMeerdereRegels")
@Qualifier("persoonTXT")
public class PersoonDAOMeerdereRegels implements PersoonDAO {
	private File bestand;
	
	@Autowired
	@Value("${persoonTXT}")
	public void setBestand(File bestand){
		this.bestand = bestand;
	}
	
	@Override
	public Iterable<Persoon> findAll(){
		if(!bestand.exists()){
			return null;
		}
		List<Persoon> personen = new ArrayList<Persoon>();
		try(BufferedReader reader = new BufferedReader(new FileReader(bestand))){
			for(String regel;(regel = reader.readLine()) != null;){
				int persoonNr = Integer.parseInt(regel);
				String voornaam = reader.readLine();
				String familienaam = reader.readLine();
				int aantalKinderen = Integer.parseInt(reader.readLine());
				personen.add(new Persoon(persoonNr, voornaam, familienaam, aantalKinderen));
			}			
		} catch (IOException ex){
			throw new PersoonDAOException(ex);
		}
		return personen;
	}
}
